package com.guo.xiao.bing.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guo.xiao.bing.common.Config;
import com.guo.xiao.bing.dao.JoinProjectMapper;
import com.guo.xiao.bing.dao.ProjectMapper;
import com.guo.xiao.bing.dao.ProjectTypeMapper;
import com.guo.xiao.bing.entity.*;
import com.guo.xiao.bing.vo.ProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProjectService {

    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    ProjectTypeMapper projectTypeMapper;
    @Autowired
    JoinProjectMapper joinProjectMapper;

    public List<Project> find() {
        return projectMapper.selectByExample(null);
    }

    public Project findById(Integer id) {
        return projectMapper.selectByPrimaryKey(id);
    }

    public Integer save(Project project) {
        return projectMapper.insert(project);
    }

    public Integer update(Project projecte) {
        return projectMapper.updateByPrimaryKeySelective(projecte);
    }

    public Integer delete(Integer id) {
        JoinProjectExample example = new JoinProjectExample();
        example.createCriteria().andOrgIdEqualTo(id);
        List<JoinProject> joinProjects = joinProjectMapper.selectByExample(example);
        for (JoinProject j : joinProjects) {
            j.setOrgId(0);

            joinProjectMapper.updateByPrimaryKeySelective(j);
        }
        return projectMapper.deleteByPrimaryKey(id);
    }

    public PageInfo<Project> pageFindProjectsByExample(Integer page) {
        ProjectExample pe = new ProjectExample();
        pe.setOrderByClause("id desc");

        PageHelper.startPage(page, Config.PAGE_SIZE);
        List<Project> projects = projectMapper.selectByExampleWithBLOBs(pe);
//        List<ProjectVo> projectVos = new ArrayList<>();

//        for (Project p : projects) {
//            ProjectType projectType = projectTypeMapper.selectByPrimaryKey(p.getProjectTypeId());
//            ProjectVo pv = new ProjectVo();
//            pv.setProjectType(projectType);
//            pv.setContent(p.getContent());
//            pv.setId(p.getId());
//            pv.setPic(p.getPic());
//            pv.setProjectTypeId(p.getProjectTypeId());
//            pv.setTime(p.getTime());
//            pv.setTitle(p.getTitle());
//            projectVos.add(pv);
//        }

        PageInfo<Project> pageInfo = new PageInfo<>(projects);

        return pageInfo;
    }
}
